package
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.filters.DropShadowFilter;
	import flash.media.Sound;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.text.TextFormatAlign;
	
	public class WordList extends Sprite
	{
		public static const GAME_OVER_EVENT:String = "gameover";
		
		private const _origWords:Array = ["BACON", "CANDY", "GRAPE", "GRAVY", "GRITS", "JUICE", "OMLET", "PEACH", "PIZZA", "SALAD", "STEAK", "BISON", "BUNNY", "CAMEL", "HORSE", "HYENA", "KOALA", "LLAMA", "PANDA", "SHARK", "TIGER", "WHALE", "AZURE", "BEIGE", "BLACK", "BROWN", "FLESH", "GREEN", "MAIZE", "OCHRE", "OLIVE", "SEPIA", "SLATE", "STEEL", "WHITE", "CHILE", "CHINA", "EGYPT", "GHANA", "HAITI", "INDIA", "ITALY", "JAPAN", "KENYA", "NEPAL", "SPAIN", "TIBET"];
		private var _wordPool:Array;
		private var _words:Array;
		private var _letterGrid:LetterGrid;
		private var _textFormat:TextFormat = new TextFormat("Eraser", 36, 0x000080, true, null, null, null, null, TextFormatAlign.CENTER);
		private var _textFields:Vector.<TextField>;
		private var _correctAnswerCount:int = 0;
		private var _correctSound:Sound;
		private var _gameOverSound:Sound;
		
		public function WordList(letterGrid:LetterGrid)
		{
			_letterGrid = letterGrid;
			_wordPool = _origWords.concat();
			_letterGrid.addEventListener(WordFoundEvent.WORD_FOUND, onWordFound);
			
			filters = [new DropShadowFilter(2, 270)];
			
			_correctSound = new Correct_sound();
			_gameOverSound = new GameOver_sound();
		}
		
		private function onWordFound(e:WordFoundEvent):void
		{
			for each(var tf:TextField in _textFields) {
				if (tf.text == e.word) tf.textColor = 0x444444;
			}
			_correctAnswerCount++;
			if (_correctAnswerCount >= 6) {
				_gameOverSound.play();
				dispatchEvent(new Event(GAME_OVER_EVENT));
				_correctAnswerCount = 0;
			}
			else {
				_correctSound.play();
			}
		}
		
		public function newGame():void
		{
			cleanUp();
			
			for (var i:int = 0; i < 6; i++) {
				
				if (_wordPool.length < 1) _wordPool = _origWords.concat();
				
				var rand:int = int(Math.random()*_wordPool.length);
				_words.push(_wordPool[rand]);
				
				var tf:TextField = new TextField();
				tf.embedFonts = true;
				tf.width = 200;
				tf.height = 40;
				tf.defaultTextFormat = _textFormat;
				tf.x = i % 3 * 200;
				tf.y = int(i / 3) * 40;
				tf.selectable = false;
				tf.text = _wordPool[rand];
				_textFields.push(tf);
				addChild(tf);
				
				_wordPool.splice(rand, 1);
			}
			
			x = Main.GAME_WIDTH / 2 - width / 2;
			y = Main.GAME_HEIGHT - height;
			
			_letterGrid.newGame(_words);
		}
		
		public function get words():Array {
			return _words;
		}
		
		private function cleanUp():void
		{
			_correctAnswerCount = 0;
			_words = new Array();
			_textFields = new Vector.<TextField>();
			while (numChildren > 0) removeChildAt(0);
		}
		
	}

}